package servlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import service.DataService;
import service.ErrorService;
import service.Password;
import service.ValidateInput;
import dataDAOImpl.MySQLOperatorDAO;
import dataDAOInterfaces.DALException;
import dataDAOInterfaces.IOperatorDAO;
import dataDTO.OperatorDTO;


/**
 * Servlet implementation class Admin
 */
public class Admin extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Admin() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */

	private RequestDispatcher dispatcher = null;
	private DataService data = new DataService();
	private ValidateInput validate = new ValidateInput();
	private IOperatorDAO opr;
	private OperatorDTO oprObj;
	private String oprName;
	private String cpr;
	private String oprId;
	private String role;
	private String page;
	private String id;
	private String ini;
	private String pass;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		page = request.getParameter("page");
		id = request.getParameter("id");
		if (isLoggedIn(request))
		{
			try
			{
				if (page.equals("1"))		// DEFAULT PAGE
				{
					this.forward(request, response, "/WEB-INF/admin/Default.jsp");
				}
				//############################################## CREATE OPERATOR PAGE ##############################################
				else if (page.equals("2"))
				{
					if (!request.getMethod().equals("POST"))
					{
						this.forward(request, response, "/WEB-INF/admin/CreateOperator.jsp");
					}
					else
					{
						this.createOperator(request, response);
					}
				}
				//############################################## EDIT OPERATOR PAGE ##############################################
				else if (page.equals("3"))
				{
					opr = new MySQLOperatorDAO();
					String status = null;
					try { status = opr.getOperator(Integer.parseInt(id)).getStatus(); }
					catch (DALException e) { System.out.println("DAL Fejl: "+e); }

					if (status.equals("1"))
					{
						if (!request.getMethod().equals("POST"))
						{
							this.setBeanData(request, response); //Her sættes data fra databasen i bønnen
						}
						else
						{
							this.updateOperator(request, response);
						}
					}
					else //Hvis operatøren er deaktiveret forwardes til default således det ikke er muligt at rette i inaktive brugere
					{
						this.forward(request, response, "/WEB-INF/admin/Default.jsp");
					}
				}

				//############################################## DEACTIVATE OPERATOR PAGE ##############################################
				else if (page.equals("4"))
				{
					this.deactivateOperator(request, response);
				}
				//############################################## ACTIVATE OPERATOR PAGE ##############################################
				else if (page.equals("5"))
				{
					this.activateOperator(request, response);
				}
				else	//Hvis page attributen i URLen er alt andet end null
				{
					this.forward(request, response, "/WEB-INF/admin/Default.jsp");
				}
			}
			catch (NullPointerException e)
			{
				//Der kastes NullPointerException hvis man ikke angiver page attributten i URLen
				//Derfor forwardes til default
				this.forward(request, response, "/WEB-INF/admin/Default.jsp");
				System.out.println("Fejl (skyldes at page attributten i URLen ikke er defineret): "+e);
			}
		}
		else
		{
			this.forward(request, response, "/Afvejningssystem");
		}
	}

	//################################################### METHODS ###################################################
	private boolean isLoggedIn(HttpServletRequest request)
	{
		HttpSession session = request.getSession();
		return session.getAttribute("user").equals("1");
	}

	private void forward(HttpServletRequest request, HttpServletResponse response, String URL) throws ServletException, IOException
	{
		dispatcher = request.getRequestDispatcher(URL);
		dispatcher.forward(request, response);
	}

	private void createError(ValidateInput validate, HttpServletRequest request)
	{
		ErrorService error = validate.createError();
		error.setError(validate.getError());
		request.setAttribute("error", error);
	}
	
	

	private void createOperator(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		oprName = request.getParameter("name");
		cpr = request.getParameter("cpr");
		oprId = request.getParameter("id");
		role = request.getParameter("role");
		if (!validate.validate(oprId, oprName, cpr, null, null, true)) //Hvis felterne ikke er udfyldt korrekt udskrives der fejlbesked
		{
			this.createError(validate, request);
			this.forward(request, response, "/WEB-INF/admin/CreateOperator.jsp");
		} 
		else	//Hvis felterne er udfyldt korrekt oprettes operatøren
		{
			opr = new MySQLOperatorDAO();
			
			String roleNr = "4";	//Rolle nummer (Default: operatør=4)
			if (role.equals("Operatør")) 			{ roleNr = "4"; }
			else if (role.equals("Værkfører")) 		{ roleNr = "3"; }
			else if (role.equals("Farmaceut")) 		{ roleNr = "2"; }
			else if (role.equals("Administrator")) 	{ roleNr = "1"; }

			String pass = new Password().generatePassword();
			String ini = iniGenerator(oprName);

			try 
			{
				opr.createOperator(new OperatorDTO(Integer.parseInt(id), oprName, ini, cpr, pass, "1", roleNr));
				this.forward(request, response, "/WEB-INF/admin/Default.jsp");
			}
			catch (DALException e) 
			{
				validate.setError("<li>ID er i brug</li>");
				this.createError(validate, request);
				this.forward(request, response, "/WEB-INF/admin/CreateOperator.jsp");
				System.out.println("DAL Fejl: "+e);
			}
			catch (Exception e) 
			{
				System.out.println("Fejl: "+e);
			}
		}
	}

	private void updateOperator(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		oprName = request.getParameter("name");
		cpr = request.getParameter("cpr");
		ini = request.getParameter("ini");
		pass = request.getParameter("pass");

		if (!validate.validate(id, oprName, cpr, ini, pass, true)) //Hvis felterne ikke er udfyldt korrekt udskrives der fejlbesked
		{
			this.createError(validate, request);
			this.forward(request, response, "/WEB-INF/admin/EditOperator.jsp");
		}
		else	//Hvis felterne er korrekt udfyldt, opdateres operatøren
		{
			try
			{
				oprObj = new OperatorDTO(Integer.parseInt(id), oprName, ini, cpr, pass, opr.getOperator(Integer.parseInt(id)).getStatus(), opr.getOperator(Integer.parseInt(id)).getRole());
				opr.updateOperator(oprObj);
				this.forward(request, response, "/WEB-INF/admin/Default.jsp");
			}
			catch (DALException e) 
			{
				System.out.println("DAL Fejl: "+e);
			}
			catch (Exception e) 
			{
				System.out.println("Fejl: "+e);
			}
		}
	}
	
	private void setBeanData(HttpServletRequest request, HttpServletResponse response)
	{
		try 
		{
			oprObj = opr.getOperator(Integer.parseInt(id));
			data.setCpr(oprObj.getCpr()); //Sætter data i bønnen så det kan vises
			data.setId(id);
			data.setIni(oprObj.getIni());
			data.setName(oprObj.getOprName());
			data.setPass(oprObj.getPassword());
			request.setAttribute("data", data);	//Sender objektet med requestet
			this.forward(request, response, "/WEB-INF/admin/EditOperator.jsp");
		} 
		catch (DALException e)
		{
			System.out.println("DAL Fejl: "+e);
		}
		catch (Exception e)
		{
			System.out.println("Fejl: "+e);
		}
	}
	
	private void activateOperator(HttpServletRequest request, HttpServletResponse response)
	{
		oprId = request.getParameter("id");
		opr = new MySQLOperatorDAO();
		try
		{
			OperatorDTO oprObj = opr.getOperator(Integer.parseInt(oprId));
			oprObj.setStatus("1");
			opr.updateOperator(oprObj);
			this.forward(request, response, "/WEB-INF/admin/Default.jsp");
		}
		catch (Exception e)
		{
			System.out.println("Fejl: "+e);
		}
	}
	
	private void deactivateOperator(HttpServletRequest request, HttpServletResponse response)
	{
		String oprId = request.getParameter("id");
		IOperatorDAO opr = new MySQLOperatorDAO();
		try
		{
			OperatorDTO oprObj = opr.getOperator(Integer.parseInt(oprId));
			oprObj.setStatus("2");
			opr.updateOperator(oprObj);
			this.forward(request, response, "/WEB-INF/admin/Default.jsp");
		}
		catch (DALException e)
		{
			System.out.println("DAL Fejl: "+e);
		}
		catch (Exception e)
		{
			System.out.println("Fejl: "+e);
		}
		
	}

	private String iniGenerator(String OprName)
	{
		String ini = "";
		String firstName = "";
		String lastName = "";

		for(int i = 0 ; i < OprName.length() ; i++)
		{
			if(!Character.isWhitespace(OprName.charAt(i)))
				firstName = firstName + OprName.charAt(i);
			if(Character.isWhitespace(OprName.charAt(i))){//finds space at index i	
				lastName = OprName.substring(i+1, OprName.length());
				break;
			}

		}
		if(lastName.equals(""))
		{
			ini = firstName.substring(0, 1).toLowerCase() + firstName.substring(firstName.length()-1, firstName.length()).toLowerCase();
		}
		else
		{
			ini = firstName.substring(0, 1).toLowerCase() + lastName.substring(0, 2).toLowerCase();
		}
		return ini;
	}

}
